#!/usr/bin/python
# coding:utf-8

import tushare as ts
import db.util_db_new as db
import db.sql_fundnv as db_sql


def _init():  # 初始化
    apicode = 'c1a96a9975761f56e12577108c8a0070f6c583bfa43181b78336b219'
    global ts_pro
    ts_pro = ts.pro_api(apicode)


def get_last_date(fundcode):
    sql = db_sql.get_fund_last_nvdate2(fundcode)
    conn = db.create_conn()
    lines, rslts = conn.query(sql)
    if lines > 0:
        last_date = rslts[0][0]
        sql2 = db_sql.del_last_nvdate2(fundcode, last_date)
        _, _ = conn.query(sql2)
    else:
        last_date = '19000101'
    db.close_conn(conn)
    # print(last_date)
    return last_date


def upd_fund_daily(fundcode):
    """
    更新场内基金日线行情数据，文档 https://tushare.pro/document/2?doc_id=127
    """
    last_date = get_last_date(fundcode)

    df = ts_pro.fund_daily(ts_code=fundcode, start_date=last_date)
    df.set_index(['ts_code', 'trade_date'])
    df = df.sort_values(by=['ts_code', 'trade_date'], ascending=[True, False])
    # print(df)

    engine = db.create_db_engine()
    # connection = engine.connect()

    df.to_sql("ts_fundDaily", engine, if_exists='append', index=True)
    db.close_db_engine(engine)


def upd_idx_daily(fundcode):
    """
    更新国内指数日线行情数据，文档 https://tushare.pro/document/2?doc_id=95
    """
    last_date = get_last_date(fundcode)

    df = ts_pro.index_daily(ts_code=fundcode, start_date=last_date)
    df.set_index(['ts_code', 'trade_date'])
    df = df.sort_values(by=['ts_code', 'trade_date'], ascending=[True, False])
    # print(df)

    engine = db.create_db_engine()
    # connection = engine.connect()

    df.to_sql("ts_fundDaily", engine, if_exists='append', index=True)
    db.close_db_engine(engine)


def upd_glb_idx_daily(fundcode):
    """
    更新国际指数日线行情数据，文档 https://tushare.pro/document/2?doc_id=211
    """
    last_date = get_last_date(fundcode)

    df = ts_pro.index_global(ts_code=fundcode, start_date=last_date, fields='ts_code,trade_date,pre_close,open,high,low,close,change,pct_chg,vol,amount')
    df.set_index(['ts_code', 'trade_date'])
    df = df.sort_values(by=['ts_code', 'trade_date'], ascending=[True, False])
    # print(df)

    engine = db.create_db_engine()
    # connection = engine.connect()

    df.to_sql("ts_fundDaily", engine, if_exists='append', index=True)
    db.close_db_engine(engine)
